<template>
    <div class="dialog">
        <el-dialog v-model="dialogVisible" center width="20%" @close="form={}">
            <div class="form" style="width: 80%;margin: 10px auto 0">
                <el-form ref="formRef" :model="form" :rules="rules" label-width="0">
                    <el-form-item prop="goodsName">
                        <el-input v-model.trim="form.goodsName" placeholder="请输入物资名称"/>
                    </el-form-item>
                    <el-form-item prop="number">
                        <el-input-number v-model.number="form.number" :min="1" placeholder="请输入物资数量"
                                         style="width: 100%"/>
                    </el-form-item>
                    <el-form-item prop="specification">
                        <el-input v-model.trim="form.specification" placeholder="请输入物资规格"/>
                    </el-form-item>
                    <el-form-item>
                        <el-upload :action="BaseConfig.imageUploadURL" :before-upload="beforeAvatarUpload"
                                   :headers="tokenHeader"
                                   :on-success="handleAvatarSuccess" :show-file-list="false" class="avatar-uploader">
                            <el-button style="width: 100%">点击上传图片文件</el-button>
                        </el-upload>
                    </el-form-item>
                    <el-form-item prop="typeId">
                        <el-select v-model="form.typeId" placeholder="请选择物资种类" style="width: 100%">
                            <el-option v-for="item in option" :key="item.typeId" :label="`${item.typeName}`"
                                       :value="item.typeId"/>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <span class="span">
                  <el-button @click="cancel(formRef)">
                      取消
                  </el-button>
                  <el-button type="primary" @click="submit(formRef)">
                    提交
                  </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang='ts' setup>
import { onBeforeMount, onUnmounted, ref } from 'vue'
import { Goods, Type } from '@/ts/type/Goods'
import { FormInstance, UploadProps } from 'element-plus'
import GoodsService from '@/api/goodsApi'
import { Message, Notification } from '@/plugins/element'
import { useToken } from '@/store'
import { BaseConfig } from '@/config/config'
import { rules } from '@/config/formConfig'
import { EventBus } from '@/utils/mitt'

const Token = useToken()
const addOrUpdateBool = ref<boolean>(false)
const tokenHeader = { Authorization: Token.token }
const dialogVisible = ref<boolean>(false)
const form = ref<Goods>({})
const formRef = ref<FormInstance>()
const option = ref<Type[]>([])
const getOptions = () => {
  GoodsService.getOptions().then(res => {
    const { data } = res
    option.value = data
  })
}

const cancel = (formEl: FormInstance | undefined) => {
  dialogVisible.value = false
  formEl?.resetFields()
}
const handleAvatarSuccess: UploadProps['onSuccess'] = response => {
  const { virtualPath } = response
  form.value.picture = virtualPath
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  if (rawFile.size / 1024 / 1024 > 1) {
    Notification.error('上传文件的大小必须小于1MB')
    return false
  }
  return true
}
const addGoods = () => {
  GoodsService.postGoods(form.value).then(res => {
    const { data } = res
    EventBus.emit('searchType', false)
    Notification.success(data)
  })
}

const update = () => {
  GoodsService.updateGoods(form.value).then(res => {
    const { data } = res
    Notification.success(data)
    EventBus.emit('searchType', false)
  })
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      try {
        if (addOrUpdateBool.value) {
          addGoods()
        } else {
          update()
        }
      } finally {
        dialogVisible.value = false
      }
    } else {
      Message.error('请重新检查表单数据')
    }
  })
}
EventBus.on('addGoods', res => {
  const { bool } = res
  form.value = {}
  addOrUpdateBool.value = bool
  dialogVisible.value = true
})
EventBus.on('updateGoods', async res => {
  const { bool, goodsId } = res
  addOrUpdateBool.value = bool
  await GoodsService.getById(goodsId).then(res => {
    const { data } = res
    form.value = data
  })
  dialogVisible.value = true
})
onBeforeMount(() => {
  getOptions()
})
// 销毁当前页面的事件总线
onUnmounted(() => {
  EventBus.off('searchType')
})
</script>

<style lang='scss' scoped>
.form {
  padding: 0 20px;
}

.span {
  display: flex;
  justify-content: space-evenly;
}
</style>